﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Drawing;

namespace LG.Web
{
    [ToolboxData("<{0}:Pager runat=server></{0}:Pager>"),
    DefaultProperty("PageBarInfo"),
    DefaultEvent("PageChanging"),
    ToolboxBitmapAttribute(typeof(MyPager))]
    public class MyPager : WebControl, IPostBackEventHandler
    {
        public MyPager()
            : base(HtmlTextWriterTag.Div)
        {
            this.Width = new Unit("100%");
            if (this.UrlPage)
            {
                this.EnableViewState = false;
            }
        }
        
        #region 变量、事件

        public event EventHandler<MyPageChangingEventArgs> PageChanging;
        private int _totalPage = 0;
        private string _pageBarTemplate = "{_Bar_}&nbsp;&nbsp;共{_TotalRecord_}条记录{_TotalPage_}页,当前第{_PageIndex_}页";
        //分页条{_Bar_}
        //共{_TotalPage_}页
        //当前第{_PageIndex_} 
        //共{_TotalRecord_}条记录
        //从{_BeginRecord_}到{_EndRecord_}
        bool _autoHide = true;
        bool _showNext = true;
        bool _showPrev = true;
        bool _showFirst = true;
        bool _showLast = true;
        bool _showSkip = true;
        bool _urlPage = false;
        string _urlKey = "lgpage";

        string _nextText = "下一页";
        string _prevText = "上一页";
        string _firstText = "首页";
        string _lastText = "尾页";
        string _skipText = "GO";
        //颜色
        string _noLinkStyle = "color:#7E7D7D;cursor:text;text-decoration:none;outline:none";
        private string _linkStyle = "color:#0063DC;outline:none";
        private string _currentLinkStyle = "color:#FF5568;cursor:text;font-weight:bold;outline:none";
        private string _digitalStyle = "color:#FF5500";

        #endregion

        #region 属性

        /// <summary>
        /// 分页条信息的模板,
        /// 分页条{_Bar_},
        /// 共{_TotalPage_}页,
        /// 当前第{_PageIndex_},
        /// 共{_TotalRecord_}条记录,
        /// 从{_BeginRecord_}到{_EndRecord_}
        /// </summary>
        [Description("分页条信息的模板:分页条{_Bar_},共{_TotalPage_}页,当前第{_PageIndex_},共{_TotalRecord_}条记录,从{_BeginRecord_}到{_EndRecord_}"),
        Category("外观"),
        Bindable(true),
        DefaultValue("{_Bar_}&nbsp;&nbsp;共{_TotalRecord_}条记录{_TotalPage_}页,当前第{_PageIndex_}页")]
        public string PageBarTemplate
        {
            get
            {
                return _pageBarTemplate;
            }
            set
            {
                _pageBarTemplate = value;
            }
        }

        [Description("分页链接的Style"),
        Bindable(true),
        Category("外观"),
        DefaultValue("color:#0063DC;outline:none")]
        public string LinkStyle
        {
            get { return _linkStyle; }
            set { _linkStyle = value; }
        }

        [Description("分页当前链接的Style"),
        Bindable(true),
        Category("外观"),
        DefaultValue("color:#FF5568;cursor:text;font-weight:bold;outline:none")]
        public string CurrentLinkStyle
        {
            get { return _currentLinkStyle; }
            set { _currentLinkStyle = value; }
        }
        
        [Description("分页无链接的Style"),
        Bindable(true),
        Category("外观"),
        DefaultValue("color:#7E7D7D;cursor:text;text-decoration:none;outline:none")]
        public string NoLinkStyle
        {
            get { return _noLinkStyle; }
            set { _noLinkStyle = value; }
        }

        [Description("分页信息数字的Style"),
        Bindable(true),
        Category("外观"),
        DefaultValue("color:#FF5500")]
        public string DigitalStyle
        {
            get { return _digitalStyle; }
            set { _digitalStyle = value; }
        }


        [Description("下一页文字"),
        Bindable(true),
        Category("外观"),
        DefaultValue("下一页")]
        public string NextText
        {
            get { return _nextText; }
            set { _nextText = value; }
        }

        [Description("上一页文字"),
        Bindable(true),
        Category("外观"),
        DefaultValue("上一页")]
        public string PrevText
        {
            get { return _prevText; }
            set { _prevText = value; }
        }

        [Description("首页文字"),
        Bindable(true),
        Category("外观"),
        DefaultValue("首页")]
        public string FirstText
        {
            get { return _firstText; }
            set { _firstText = value; }
        }

        [Description("尾页文字"),
        Bindable(true),
        Category("外观"),
        DefaultValue("尾页")]
        public string LastText
        {
            get { return _lastText; }
            set { _lastText = value; }
        }

        [Description("跳转按钮文字"),
        Bindable(true),
        Category("外观"),
        DefaultValue("GO")]
        public string SkipText
        {
            get { return _skipText; }
            set { _skipText = value; }
        }

        [Description("url分页时的页参数"),
        Bindable(true),
        Category("外观"),
        DefaultValue("lgpage")]
        public string UrlKey
        {
            get { return _urlKey; }
            set { _urlKey = value; }
        }

        [Description("是否启用url分布"),
        Bindable(false),
        Category("行为"),
        DefaultValue(false)]
        public bool UrlPage
        {
            get { return _urlPage; }
            set { _urlPage = value; }
        }

        [Description("是否在不用翻页时自动隐藏"),
        Bindable(false),
        Category("行为"),
        DefaultValue(true)]
        public bool AutoHide
        {
            get { return _autoHide; }
            set { _autoHide = value; }
        }


        [Description("是否显示下一页链接"),
        Bindable(false),
        Category("行为"),
        DefaultValue(true)]
        public bool ShowNext
        {
            get { return _showNext; }
            set { _showNext = value; }
        }

        [Description("是否显示上一页链接"),
        Bindable(false),
        Category("行为"),
        DefaultValue(true)]
        public bool ShowPrev
        {
            get { return _showPrev; }
            set { _showPrev = value; }
        }

        [Description("是否显示首页链接"),
        Bindable(false),
        Category("行为"),
        DefaultValue(true)]
        public bool ShowFirst
        {
            get { return _showFirst; }
            set { _showFirst = value; }
        }

        [Description("是否显示末页链接"),
        Bindable(false),
        Category("行为"),
        DefaultValue(true)]
        public bool ShowLast
        {
            get { return _showLast; }
            set { _showLast = value; }
        }

        [Description("是否显示跳转按键"),
        Bindable(false),
        Category("行为"),
        DefaultValue(true)]
        public bool ShowSkip
        {
            get { return _showSkip; }
            set { _showSkip = value; }
        }

        [Description("总记录数"),
        Bindable(false),
        Category("行为"),
        DefaultValue(100)]
        public int TotalRecord
        {
            get { return ViewState["_TotalRecord_"] == null ? 100 : (int)ViewState["_TotalRecord_"]; }
            set
            {
                foreach (char c in System.Convert.ToString(value))
                {
                    if (!Char.IsNumber(c))
                    {
                        ViewState["_TotalRecord_"] = 0;
                        break;
                    }
                }
                ViewState["_TotalRecord_"] = value;
            }
        }

        [Description("每页显示记录数"),
        Bindable(true),
        Category("行为"),
        DefaultValue(10)]
        public int PageSize
        {
            get { return ViewState["_PageSize_"] == null ? 10 : (int)ViewState["_PageSize_"]; }
            set
            {
                foreach (char c in System.Convert.ToString(value))
                {
                    if (!Char.IsNumber(c))
                    {
                        ViewState["_PageSize_"] = 1;
                        return;
                    }
                }
                ViewState["_PageSize_"] = value;
            }
        }

        [Description("总页数"),
        Bindable(true),
        Category("行为"),
        DefaultValue(0)]
        public int TotalPage
        {
            get { return _totalPage; }
        }

        [Description("每条的页链接数"),
        Bindable(true),
        Category("行为"),
        DefaultValue(10)]
        public int BarSize
        {
            get { return ViewState["_BarSize_"] == null ? 10 : (int)ViewState["_BarSize_"]; }
            set
            {
                foreach (char c in System.Convert.ToString(value))
                {
                    if (!Char.IsNumber(c))
                    {
                        ViewState["_BarSize_"] = 10;
                        break;
                    }
                }
                ViewState["_BarSize_"] = value;
            }
        }

        [Description("当前页值"),
        Bindable(true),
        Category("行为"),
        DefaultValue(1)]
        public int PageIndex
        {
            get { return ViewState["_PageIndex_"] == null ? 1 : (int)ViewState["_PageIndex_"]; }
            set {
                if (value <= 0)
                {
                    ViewState["_PageIndex_"] = 1;
                }
                else
                {
                    ViewState["_PageIndex_"] = value;
                }
            }
        }

        #endregion

        protected virtual void OnPageChanging(MyPageChangingEventArgs e)
        {
            if (PageChanging != null)
            {
                PageChanging(this, e);
            }
        }

        public void RaisePostBackEvent(string eventArgument)
        {
            if (UrlPage)
                return;
            int pageindex;
            if (!int.TryParse(eventArgument, out pageindex))
            {
                pageindex = 1;
            }
            this.PageIndex = pageindex;
            MyPageChangingEventArgs e = new MyPageChangingEventArgs(this.PageIndex);
            OnPageChanging(e);
        }

        /// <summary>
        /// 将些控件呈现给指定的输出参数
        /// </summary>
        /// <param name="writer">要写出到的HTML编写器</param>
        protected override void RenderContents(HtmlTextWriter writer)
        {
            if (string.IsNullOrEmpty(this.PageBarTemplate))
            {
                base.RenderContents(writer);
                return;
            }
            //计算
            
            this._totalPage = ((this.TotalRecord / this.PageSize) * this.PageSize == this.TotalRecord) ? (this.TotalRecord / this.PageSize) : ((this.TotalRecord / this.PageSize) + 1);
            if (PageIndex > TotalPage)
            {
                PageIndex = TotalPage;
            }
            int BeginRecord = (this.PageIndex - 1) * this.PageSize + 1;
            int EndRecord = this.PageIndex * this.PageSize;
            EndRecord = (EndRecord > this.TotalRecord) ? this.TotalRecord : EndRecord;
            //没有数据
            if (this.TotalRecord == 0 || this.TotalPage == 0)
            {
                base.RenderContents(writer);
                return;

            }
            //自动隐藏
            if (AutoHide && TotalRecord <= PageSize)
            {
                writer.Write("<!-- LGHelper控件自动隐藏 -->");
                base.RenderContents(writer);
                return;
            }
            //分页信息
            string barinfo = string.Empty;
            barinfo = PageBarTemplate;
            string digitalBeginStyle = "<span style='"+DigitalStyle+"'>";
            string digitalEndStyle = "</span>";
            barinfo = barinfo.Replace("{_TotalPage_}", digitalBeginStyle + TotalPage.ToString() + digitalEndStyle);
            barinfo = barinfo.Replace("{_PageIndex_}", digitalBeginStyle + PageIndex.ToString() + digitalEndStyle);
            barinfo = barinfo.Replace("{_TotalRecord_}", digitalBeginStyle + TotalRecord.ToString() + digitalEndStyle);
            barinfo = barinfo.Replace("{_BeginRecord_}", digitalBeginStyle + BeginRecord.ToString() + digitalEndStyle);
            barinfo = barinfo.Replace("{_EndRecord_}", digitalBeginStyle + EndRecord.ToString() + digitalEndStyle);

            //得到分页后的尾数(比如：总共58页，按10页规格显示，则尾数为8)
            int SingleNumber = this.TotalPage - (TotalPage / BarSize) * BarSize;
            int IntPageForMax = (this.PageIndex - 1) / BarSize;
            int MinInt = (1 + BarSize * IntPageForMax);
            int MaxInt = ((IntPageForMax + 1) * BarSize) > TotalPage ? TotalPage : ((IntPageForMax + 1) * BarSize);
            //下面是有数据里
            StringBuilder pagelist = new StringBuilder(string.Empty);
            for (int i = MinInt; i <= MaxInt; i++)
            {
                #region  前部处理
                
                if (i == MinInt)
                {
                    //首页处理
                    if (ShowFirst)
                    {
                        if (PageIndex == 1)
                        {
                            pagelist.AppendFormat(getLink(false), NoLinkStyle, FirstText);
                        }
                        else
                        {
                            pagelist.AppendFormat(getLink(true), LinkStyle, FirstText, getPostBack(1));
                        }
                    }
                    //上一页处理
                    if (ShowPrev)
                    {
                        if (PageIndex == 1)
                        {
                            pagelist.AppendFormat(getLink(false), NoLinkStyle, PrevText);
                        }
                        else
                        {
                            pagelist.AppendFormat(getLink(true), LinkStyle, PrevText, getPostBack(PageIndex - 1));
                        }
                    }
                    //上一翻处理
                    if (PageIndex > BarSize)
                    {
                        pagelist.AppendFormat(getLink(true), LinkStyle, "...", getPostBack(IntPageForMax * BarSize));
                    }
                }
                #endregion 

                //正常页处理
                if (PageIndex == i)
                {
                    pagelist.AppendFormat(getLink(false), CurrentLinkStyle, i);
                }
                else
                {
                    pagelist.AppendFormat(getLink(true), LinkStyle, i, getPostBack(i));
                }

                #region 后部处理
 
                if (i == MaxInt)
                {
                    //下一翻处理
                    if (MaxInt<TotalPage)
                    {
                        pagelist.AppendFormat(getLink(true), LinkStyle, "...", getPostBack(((IntPageForMax + 1) * BarSize) + 1));
                    }

                    //下一页处理
                    if (ShowNext)
                    {
                        if (PageIndex == TotalPage)
                        {
                            pagelist.AppendFormat(getLink(false), NoLinkStyle, NextText);
                        }
                        else
                        {
                            pagelist.AppendFormat(getLink(true), LinkStyle, NextText, getPostBack(PageIndex + 1));
                        }
                    }
                    //末页处理
                    if (ShowLast)
                    {
                        if (PageIndex == TotalPage)
                        {
                            pagelist.AppendFormat(getLink(false), NoLinkStyle, LastText);
                        }
                        else
                        {
                            pagelist.AppendFormat(getLink(true), LinkStyle, LastText, getPostBack(TotalPage));
                        }
                    }
                }
                #endregion 
            }

            //转到指定页
            if (ShowSkip && (TotalRecord>BarSize) && !UrlPage)
            {
                pagelist.AppendFormat(" &nbsp;到第<input type='text' id='{0}goto' value='{1}' style='width:30px;' onchange=\"this.value=this.value.replace(/\\D+/g,'')\"  onkeyup=\"this.value=this.value.replace(/\\D+/g,'')\" />页", this.UniqueID, PageIndex);
                pagelist.AppendFormat("<input type='button' value='{2}' onclick=\"__doPostBack('{0}',document.getElementById('{1}').value)\">", this.UniqueID, this.UniqueID + "goto",SkipText);
            }

            barinfo = barinfo.Replace("{_Bar_}", pagelist.ToString());
            writer.Write(barinfo);
            base.RenderContents(writer);
        }

        //得到客户端回调
        string getPostBack(object index)
        {
            if (UrlPage)
            {
               return index.ToString();
            }
            else
            {
                return Page.ClientScript.GetPostBackEventReference(this, index.ToString());
            }
        }

        //得到链接的字符串格式
        string getLink(bool isLink)
        {
            if (isLink)
            {
                if (UrlPage)
                {
                    string url = PageHelper.SetUrlParams(UrlKey, "{2}");
                    return " <a  href=\"" + url + "\"  style='{0}'>{1}</a>";
                }
                else
                {
                    return " <a  href=\"javascript:{2}\"  style='{0}'>{1}</a>";
                }
            }
            else
            {
                return " <a href='javascript:;' style='{0}'>{1}</a>";
            }
        }
    }
}
